package com.dmx.cep.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
import org.mozilla.intl.chardet.nsPSMDetector;

/**
 * Detect the encoding of the input file
 * @author Ginge
 *
 */
public class EncodingDetecter {
	private static Log log = LogFactory.getLog(EncodingDetecter.class);
	public  String preParse(String filename,String lanCode) throws IOException{
		URL url = null;
		String encodeType=null;
		try {
			url=new URL("file:"+filename);
		} catch (MalformedURLException e1) {
			log.error(e1.getMessage(),e1);
			return null;
		}
		BufferedInputStream imp = null;
		try {
			imp = new BufferedInputStream(url.openStream());
		} catch (IOException e1) {
			log.error(e1.getMessage(),e1);
			return null;
		}

		if("zh_CN".equalsIgnoreCase(lanCode)){
			encodeType=new EncodingDetecter().detectSimplefiedChinese(imp);
		}else{
			encodeType=new EncodingDetecter().detect(imp);
		}

		return encodeType;
	}
	public static void main(String[] argv) {
//		String filename="D:\\newworkspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp1\\work\\Catalina\\localhost\\appserver\\upload_11c12d57_11d94c53f5c__7faa_00000003.tmp";
        EncodingDetecter ed=new EncodingDetecter();
        try{
        String entype=ed.preParse("C:\\Documents and Settings\\magicyang\\桌面\\CEP\\ch-en.srt","zh_CN");
        System.out.println(entype);
        }
        catch(Exception e){
        	log.error(e.getMessage(),e);
        }
	}

	public String detect(URL url)
	{
		BufferedInputStream imp = null;
		try {
			imp = new BufferedInputStream(url.openStream());
		} catch (IOException e1) {
			log.error(e1.getMessage(),e1);
		}

		return this.detect(imp);
	}


	public String detect(File file)
	{
		FileInputStream is = null;
		try {
			is = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			log.error(e.getMessage(),e);
		}

		return this.detect(is);
	}

	/**
	 * 
	 * @param imp
	 * @return
	 */
	public String detect(InputStream imp) {


		String detected = "unknown";

		if(imp == null)
		{
			return detected;
		}

		nsDetector det = new nsDetector(nsPSMDetector.MAX_VERIFIERS);

		nsICharsetDetectionObserverImpl nsb = new nsICharsetDetectionObserverImpl();

		det.Init(nsb);

		byte[] buf = new byte[1024];

		int len;
		boolean done = false;
		boolean isAscii = true;

		try {
			while ((len = imp.read(buf, 0, buf.length)) != -1) {

				// Check if the stream is only ascii.
				if (isAscii)
					isAscii = det.isAscii(buf, len);

				// DoIt if non-ascii and not done yet.
				if (!isAscii && !done)
					done = det.DoIt(buf, len, false);
			}
		} catch (IOException e) {
			log.error(e.getMessage(),e);
		}
		det.DataEnd();

		if(isAscii)
		{
			detected = "ASCII";
		}else
		{
			if (nsb.getDetected() == null) {// 如果没找到，则找到最可能的那些字符集
				String prob[] = det.getProbableCharsets();
				if(prob.length > 0)
				{
					detected = prob[0];
				}
			}

			else
			{
				detected = nsb.getDetected();
			}
		}

		return detected;



	}


	/**
	 * @param args
	 */
	public String detectSimplefiedChinese(InputStream imp) {


		String detected = "unknown";

		if(imp == null)
		{
			return detected;
		}

		nsDetector det = new nsDetector(nsPSMDetector.SIMPLIFIED_CHINESE);

		nsICharsetDetectionObserverImpl nsb = new nsICharsetDetectionObserverImpl();

		det.Init(nsb);

		byte[] buf = new byte[1024];

		int len;
		boolean done = false;
		boolean isAscii = true;

		try {
			while ((len = imp.read(buf, 0, buf.length)) != -1) {

				// Check if the stream is only ascii.
				if (isAscii)
					isAscii = det.isAscii(buf, len);

				// DoIt if non-ascii and not done yet.
				if (!isAscii && !done)
					done = det.DoIt(buf, len, false);
			}
		} catch (IOException e) {
			log.error(e.getMessage(),e);
		}
		det.DataEnd();

		if(isAscii)
		{
			detected = "ASCII";
		}else
		{
			if (nsb.getDetected() == null) {// 如果没找到，则找到最可能的那些字符集
				String prob[] = det.getProbableCharsets();
				if(prob.length > 0)
				{
					detected = prob[0];
				}
			}

			else
			{
				detected = nsb.getDetected();
			}
		}

		return detected;



	}

	class nsICharsetDetectionObserverImpl implements
			nsICharsetDetectionObserver {
		private String detected;

		public void Notify(String arg0) {
			// TODO Auto-generated method stub
			this.detected = arg0;
		}

		public String getDetected() {
			return detected;
		}

		public void setDetected(String detected) {
			this.detected = detected;
		}

	}

}
